/**
 * Copyright (C) 2018-2022
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制
 */
package co.yixiang.controller.buyer.order;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.yixiang.common.annotation.AnonymousAccess;
import co.yixiang.common.annotation.Log;
import co.yixiang.common.annotation.NoRepeatSubmit;
import co.yixiang.common.enums.OrderInfoEnum;
import co.yixiang.common.enums.OrderLogEnum;
import co.yixiang.common.enums.ResultCode;
import co.yixiang.common.exception.BadRequestException;
import co.yixiang.common.utils.ResultUtil;
import co.yixiang.common.utils.SecurityUtils;
import co.yixiang.common.vo.ResultMessage;
import co.yixiang.dozer.service.IGenerator;
import co.yixiang.modules.activity.service.YxStorePinkService;
import co.yixiang.modules.goods.entity.vo.YxStoreProductVo;
import co.yixiang.modules.member.entity.domain.YxUser;
import co.yixiang.modules.member.service.YxUserService;
import co.yixiang.modules.mp.service.YxTemplateService;
import co.yixiang.modules.order.cart.entity.enums.DeliveryMethodEnum;
import co.yixiang.modules.order.order.entity.domain.YxStoreOrder;
import co.yixiang.modules.order.order.entity.domain.YxStoreOrderStatus;
import co.yixiang.modules.order.order.entity.dto.OrderCountDto;
import co.yixiang.modules.order.order.entity.dto.YxStoreOrderCancelDto;
import co.yixiang.modules.order.order.entity.dto.YxStoreOrderDto;
import co.yixiang.modules.order.order.entity.dto.YxStoreOrderQueryCriteria;
import co.yixiang.modules.order.order.entity.enums.DeliverStatusEnum;
import co.yixiang.modules.order.order.entity.enums.OrderStatusEnum;
import co.yixiang.modules.order.order.entity.enums.OrderTypeEnum;
import co.yixiang.modules.order.order.entity.vo.YxStoreOrderVoF;
import co.yixiang.modules.order.order.service.OrderService;
import co.yixiang.modules.order.order.service.YxStoreOrderService;
import co.yixiang.modules.order.order.service.YxStoreOrderStatusService;
import co.yixiang.modules.security.entity.vo.AuthUser;
import co.yixiang.modules.shop.entity.dto.ExpressInfo;
import co.yixiang.modules.shop.entity.dto.WechatUserDto;
import co.yixiang.modules.shop.entity.param.ExpressParam;
import co.yixiang.modules.shop.service.ExpressService;
import co.yixiang.modules.shop.service.YxExpressService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.spring.web.readers.operation.ResponseMessagesReader;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author hupeng
 * @date 2019-10-14
 */
@Api(tags = "商城:订单管理")
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderBuyerController {

    @Value("${yshop.apiUrl}")
    private String apiUrl;
    @Autowired
    private  IGenerator generator;
    @Autowired
    private  YxStoreOrderService yxStoreOrderService;
    @Autowired
    private  YxStoreOrderStatusService yxStoreOrderStatusService;
    @Autowired
    private  YxExpressService yxExpressService;
    @Autowired
    private  YxUserService userService;
    @Autowired
    private  YxTemplateService templateService;
    @Autowired
    private  ExpressService expressService;

    @ApiOperation(value = "查询订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sn", value = "订单号", paramType = "query"),
            @ApiImplicitParam(name = "orderStatus", value = "订单状态:UNPAID/未支付:DELIVERED/待收货:COMPLETED:已完成/REFUND:售后/CANCELLED:取消", paramType = "query"),
            @ApiImplicitParam(name = "orderType", value = "订单类型:默认为普通订单:NORMAL,ADOPT", paramType = "query")
    })
    @GetMapping
    public ResultMessage<Map<String, Object>> getYxStoreOrders(YxStoreOrderQueryCriteria criteria, Pageable pageable) {
        if (ObjectUtil.isEmpty(criteria.getOrderType())) {
            criteria.setOrderType(OrderTypeEnum.NORMAL.name());
        }
        Map<String, Object> stringObjectMap = yxStoreOrderService.queryAllToVo(criteria, pageable);
        return ResultUtil.data(stringObjectMap);
    }

    @Log("查询订单详情")
    @ApiOperation(value = "查询订单详情")
    @GetMapping(value = "detail/{sn}")
    public ResultMessage<YxStoreOrderVoF> getYxStoreOrderDetail(@PathVariable String sn) {
        final YxStoreOrderVoF order = yxStoreOrderService.queryOrderDetail(sn);
        return ResultUtil.data(order);
    }

    @Log("查询订单不同状态的数量")
    @ApiOperation(value = "查询订单不同状态的数量")
    @GetMapping(value = "statusSize")
    public ResultMessage<Map<String, Integer>> getOrderStatusSize() {
        final Map<String, Integer> stringIntegerMap = yxStoreOrderService.orderStatusSizeBYUid();
        return ResultUtil.data(stringIntegerMap);
    }



    @ApiOperation(value = "取消订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderSn", value = "订单编号",  paramType = "path"),
            @ApiImplicitParam(name = "reason", value = "取消原因",  paramType = "query")
    })
    @PostMapping(value = "/{orderSn}/cancel")
    public ResultMessage<Object> cancel(@PathVariable String orderSn, @RequestBody YxStoreOrderCancelDto cancelDto) {
        yxStoreOrderService.cancel(orderSn, cancelDto.getReason());
        return ResultUtil.success();
    }

    @ApiOperation(value = "确认收货")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderSn", value = "订单编号",  paramType = "path"),
    })
    @PostMapping(value = "/take/{orderSn}")
    public ResultMessage<Object> take(@PathVariable String orderSn) {
        yxStoreOrderService.take(orderSn);
        return ResultUtil.success();
    }

    @ApiOperation(value = "售后")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderSn", value = "订单编号",  paramType = "path"),
            @ApiImplicitParam(name = "reason", value = "取消原因",  paramType = "query")
    })
    @PostMapping(value = "/{orderSn}/reback")
    public ResultMessage<Object> afterSale(@PathVariable String orderSn, @RequestBody YxStoreOrderCancelDto cancelDto) {
        yxStoreOrderService.afterSale(orderSn, cancelDto.getReason());
        return ResultUtil.success();
    }

    @PostMapping("/express/{sn}")
    @ApiOperation(value = "获取物流信息", notes = "获取物流信息", response = ExpressParam.class)
    public ResultMessage<ExpressInfo> express(@PathVariable String sn) {
       YxStoreOrder order = yxStoreOrderService.getBySn(sn);
        final AuthUser authUser = SecurityUtils.getAuthUser();
        if(!order.getUid().equals(authUser.getUuid())) {
            return ResultUtil.error(ResultCode.ORDER_NOT_USER);
        }
        if (order.getOrderStatus().equals(OrderStatusEnum.DELIVERED.name()) && ObjectUtil.isNotEmpty(order.getLogisticsNo()) && ObjectUtil.isNotEmpty(order.getLogisticsCode())) {
           ExpressInfo expressInfo = expressService.getExpressInfo(order.getSn(), order.getLogisticsCode(), order.getLogisticsNo());
           if (!expressInfo.isSuccess()) {
               throw new BadRequestException(expressInfo.getReason());
           }
           return ResultUtil.data(expressInfo);
       }
        return ResultUtil.error(ResultCode.PARAMS_ERROR);
    }
}
